package com.songshuai.webapi.common.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;


public class WeChatUtil {


    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";

    /**
     * 解密数据
     *
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData,
                                 String sessionKey, String iv) {
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSON.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK)
                        .getString(APPID);
                if (!appId.equals(decryptAppid)) {
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {

        String appId = "wx728e6786c6727062";
        String encryptedData = "FLozmq+jYdwdHGpWhStUcM3ZYt6sEXk94XTTzkSvq4wTbcBF4w8G3ZSdJAoM1prU3RnPdtpFwq/JbjhlWEXomwic9RUTRIINv3OOB+hfsj5c0FjxEDASLUQGzOla88+GSnx8fQFnCHVaam05cBtfvVOShqVCPSiDmRDeJiITQcuE2+SZjdPJ9d3rRW2UEe/zIu5X+OcJ2wDdnYLjISenSw==";
        String sessionKey = "GJT1zbEXD8V7xOZVjWyNyQ==";
        String iv = "mqcJq/v9AyL7Bg0M9N4pQg==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }
}



